package sql

// 大小写转换过滤器
import (
	"regexp"

	"github.com/xormplus/core"
)

type MSSQLFilter struct {
	do func(sql string, dialect core.Dialect, table *core.Table) string
}

func (s *MSSQLFilter) _do() func(sql string, dialect core.Dialect, table *core.Table) string {

	var keywords1 = regexp.MustCompile("([\\s\\.=<>\\|,\\(])([Uu][Ss][Ee][Rr]|[Rr][Uu][Ll][Ee]|[Pp][Ll][Aa][Nn])([\\s\\.=<>\\|,\\)]|$)")
	var keywords2 = regexp.MustCompile("[a-zA-Z0-9]\\s*([\\s\\.=<>\\|,\\(])([Gg][Rr][Oo][Uu][Pp]|[Oo][Rr][Dd][Ee][Rr])([\\.=<>\\|,\\)]|$)")
	var notGroupBy = regexp.MustCompile("[a-zA-Z0-9]\\s*([\\s\\.=<>\\|,\\(])([Gg][Rr][Oo][Uu][Pp]|[Oo][Rr][Dd][Ee][Rr])(\\s+[^B][^Y])")
	var mySqlQuote = regexp.MustCompile("`([^`]+)`")

	return func(sql string, dialect core.Dialect, table *core.Table) string {

		sql = keywords1.ReplaceAllString(sql, `$1[$2]$3`)
		sql = keywords2.ReplaceAllString(sql, `$1[$2]$3`)
		sql = notGroupBy.ReplaceAllString(sql, `$1[$2]$3`)
		sql = mySqlQuote.ReplaceAllString(sql, "[$1]")

		return sql
	}
}

func (s *MSSQLFilter) Do(sql string, dialect core.Dialect, table *core.Table) string {

	if s.do == nil {
		s.do = s._do()
	}

	return s.do(sql, dialect, table)
}
